/**
 * desc: 部署脚本
 * author: zyEros
 * time: 2015/4/8
 */

var cp = require("child_process"),
    fs = require("fs"),
    tool = require("./libs/tool"),
    updateNpm = require("./libs/updateNpm"),
    moduleFileExists = fs.existsSync("./.build/node_modules"),
    argvArr = require("./config"),
    cmd;

cmd = tool.getCmdValue(argvArr, process.argv.concat());

tool.startWaitLog();
cp.exec("cd ./.build && git pull", function (err, stdout) {
    tool.stopWaitLog();

    if (err) {
        console.log("\n" + err);
        console.log("build git pull faild!");
        process.exit(0);
    } else if (/Already up-to-date/ig.test(stdout)) {
        var next = [];

        for (var i = 0, len = argvArr.length; i < len; i++) {
            var item = argvArr[i];

            if (cmd & Math.pow(2, i)) {
                next.push(item.fn);
            }
        }

        if (!moduleFileExists) {
            updateNpm(function () {
                if (next && next.length) {
                    next.shift()(next);
                }
            });
        } else if (next && next.length) {
            next.shift()(next);
        }

    } else {
        console.log("部署脚本更新完成，请重新启用部署脚本...");
    }
});